package com.heima.nio.bytebuffer;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件读取 使用 ByteBuffer + Channel
 * @author ZhengDp
 * @Date 2023/6/22 16:15
 */
@Slf4j
public class TestByteBuffer {

    public static void main(String[] args) {
        // FileChannel
        try (FileChannel channel = new FileInputStream("C:\\MyStudySpace\\Code\\basic-code\\netty-test\\data.txt").getChannel()) {
            // 准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            // 从 channel 中读取数据，将数据写入Buffer
            while(true) {
                int len = channel.read(buffer);
                log.info("读取到的字节：{}" ,len);
                if(len == -1 ) {
                    break;
                }
                // 打印 buffer 内容
                buffer.flip();
                while(buffer.hasRemaining()) {
                    byte b = buffer.get();
                    log.info("实际字节: {}",(char)b);
                }
                buffer.clear();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
